<?php

/**
 * Yii Controller HotdealController
 *
 * @author trongkhoi
 * @since Oct 7, 2013 - 7:41:39 PM
 */
class HotdealController extends FrontController
{

    public $layout = '//layouts/browser';

    private function criteria()
    {
        $crite = new CDbCriteria();
        $crite->with = array('serviceItem');
        $crite->condition = 'serviceItem.author_id NOT IN (6,6227,6230,6233,6234,6235,6237,6238,6329,6565,6698)';
//
//        $crite->with = array('appoint', 'appoint.service');
//        $crite->addCondition('service.author_id NOT IN (6,6227,6230,6233,6234,6235,6237,6238,6329,6565,6698)');
        //        $crite->with = array('serviceItem');
//        $crite->condition = 'serviceItem.book_online>0';
////
//        $crite->with = array('appoint', 'appoint.service');
//        $crite->addCondition('service.book_online>0');
        $crite->addCondition('t.start_time<' . time());
        $crite->addCondition('t.end_time>' . time());
        $crite->compare('t.merchant_status', Hotdeal::MERCHANT_ACTIVE);
        $crite->limit = $this->currentLimit;

        return $crite;
    }

    public function actionIndex()
    {
        Yii::app()->session['offset_gallery'] = 0;
        Yii::app()->session['offset_list'] = 0;

        $crite = $this->criteria();

        $model = Hotdeal::model()->findAll($crite);
        $this->render('index', array('model' => $model));
    }

    public function actionGallery()
    {
        $offset = Yii::app()->session['offset_gallery'] + $this->currentLimit;

        $crite = $this->criteria();
        $crite->offset = $offset;

        Yii::app()->session['offset_gallery'] = $offset;

        $model = Hotdeal::model()->findAll($crite);
        if ($model != NULL)
        {
            echo $this->renderPartial('gallery', array('model' => $model));
            Yii::app()->end();
        }
        else
        {
            echo 'ok';
            Yii::app()->end();
        }
    }

    public function actionList()
    {
        $offset = Yii::app()->session['offset_list'] + $this->currentLimit;

        $crite = $this->criteria();
        $crite->offset = $offset;

        Yii::app()->session['offset_list'] = $offset;

        $model = Hotdeal::model()->findAll($crite);
        if ($model != NULL)
        {
            echo $this->renderPartial('list', array('model' => $model));
        }
        else
        {
            echo 'ok';
        }
    }

    public function actionBooking()
    {
        $this->layout = '//layouts/booking';
        if (!isset($_GET['service']))
        {
            throw new CHttpException(404, 'Not found');
        }

        if (Yii::app()->user->isGuest)
        {
            $customer = new Users();
            if (isset($_POST['ajax']) && $_POST['ajax'] === 'book-form')
            {
                echo CActiveForm::validate($customer);
                Yii::app()->end();
            }
        }
        else
        {
            $customer = Users::model()->findByPk(Yii::app()->user->id);
        }
        $status = 1;

        $hotdeal = Hotdeal::model()->find("sid=:sid", array(":sid" => $_GET['service']));
        $model = $hotdeal->service;
        //Check customer of merchant is block 
        $check_cus_biz = Customer::checkCustomerBelongToBiz($customer->id, $model->author_id);
        if ($check_cus_biz)
        {
            if ($check_cus_biz->status == Customer::STATUS_BLOCK)
            {
                $status = 0;
                Yii::app()->user->setFlash('error', Yii::t('frontend','Your account is blocked with this merchant'));
            }
        }
        if ($model->user->status == Users::STATUS_BLOCK)
        {
            $status = 0;
            Yii::app()->user->setFlash('error', Yii::t('frontend','Merchant not available'));
        }
        /**
         * For Merchant Trial
         */
        elseif ($model->user->status == Users::STATUS_TRIAL)
        {
            Yii::app()->request->redirect(Yii::app()->createUrl('frontend/booking/trialBooking', array('service' => $model->sid)));
        }
        if ($status == 0)
        {
            $this->render('error_page');
        }
        else
        {	
            $this->render('booking/index', array(
                'service' => $model,
                'hotdeal' => $hotdeal,
                'customer' => $customer
            ));
        }
    }

    public function actionValidateForm()
    {
        $service = Service::getRecordbySid($_POST['sid']);

        if (Yii::app()->user->isGuest)
        {
            /**
             * Booking at Customer's Home: Validate customer address
             */
            if ($service->book_online == Service::BOOKING_CUSTOMER_HOME)
            {
                $customer = new CustomerBookForm('validate_address');
            }
            else
            {
                $customer = new CustomerBookForm;
            }
            $customer->firstname = $_POST['fname'];
            $customer->lastname = $_POST['lname'];
            $customer->email = $_POST['email'];
            $customer->mobile_phone = $_POST['phone'];
            $customer->occupation = $_POST['occupation'];
            $customer->address = $_POST['address'];
            $customer->postal_code = $_POST['postal_code'];
        }
        else
        {
            $customer = Users::model()->findByPk(Yii::app()->user->getId());
            if ($service->book_online == Service::BOOKING_CUSTOMER_HOME)
            {
                $customer->setscenario("validate_address");
            }
            $customer->firstname = $_POST['fname'];
            $customer->lastname = $_POST['lname'];
            $customer->email = $_POST['email'];
            $customer->mobile_phone = $_POST['phone'];
            $customer->occupation = $_POST['occupation'];
            $customer->address = $_POST['address'];
            $customer->postal_code = $_POST['postal_code'];
        }

        if ($customer->validate())
        {
            /**
             * Check has discount on this period
             * Caculate final price by discount and merchant tax
             */
            $staff_time = $_POST['time_staff'];
            $separatedData = explode('_', $staff_time);
            $time = $separatedData[1];
            $date = strtotime(str_replace('/', '-', $_POST['date']));
            $discount_by_time = Hotdeal::getDiscountByTime($service->sid, $date, $time);
            $discount_value = $discount_by_time ? $service->price * $discount_by_time / 100 : 0;

            $tax = $service->user->tax ? $service->user->tax->value : 0;
            $tax_value = $service->price * $tax / 100;
            $final_price = $service->price + $tax_value - $discount_value;
            echo json_encode(array(
                'status' => 1,
                'tax' => $tax,
                'tax_value' => $tax_value,
                'discount' => $discount_by_time,
                'discount_value' => $discount_value,
                'final_price' => $final_price
            ));
            Yii::app()->end();
        }
        else
        {
            echo json_encode(array(
                'status' => 0,
                'msg' => CHtml::errorSummary($customer)
            ));
            Yii::app()->end();
        }
    }

    /**
     * create a new appoinment
     * @return type
     */
    public function actionCreateAppt()
    {
        //service id
        $s_id = $_POST['sid'];
        $service = Service::getRecordbySid($s_id);

        //customer id
        $cus_id = null;
        //customer email
        $cus_email = null;

        //create Customer
        if (Yii::app()->user->isGuest)
        {
            //check customer by email
            $cus = Users::getRecordByEmail($_POST['email']);

            //if user exited in tbl_user
            if ($cus != NULL)
            {

                //kiem tra xem user co thuoc biz khong
                $check_cus_biz = Customer::checkCustomerBelongToBiz($cus->id, $service->biz->id);

                //neu customer la khach hang cua biz
                //lay id cua customer
                if ($check_cus_biz)
                {
                    $cus_id = $check_cus_biz->id;
                }
                else
                {

                    $new_cus = $this->createCustomerBiz($cus->id, $service->biz->id);
                    $cus_id = $new_cus->id;
                }
            }
            else //if email not exited in tbl_user
            {
                //create new user in
                $user = $this->createNewUser();

                //create new customer in tbl_customer
                $new_cus = $this->createCustomerBiz($user->id, $service->biz->id);
                $cus_id = $new_cus->id;
            }
        }
        //update Customer
        else
        {
            $customer = Users::model()->findByPk(Yii::app()->user->getId());
            $customer->firstname = $_POST['fname'];
            $customer->lastname = $_POST['lname'];
            $customer->email = $_POST['email'];
            $customer->mobile_phone = $_POST['phone'];
            $customer->occupation = $_POST['occupation'];
            $birthday = ($_POST['birthday'] != '') ? str_replace('/', '-', $_POST['birthday']) : NULL;
            $customer->birthday = strtotime($birthday);
            $customer->save();

            //kiem tra customer hien tai  co thuoc biz khong?
            $check_cus_biz = Customer::checkCustomerBelongToBiz($customer->id, $service->biz->id);

            if ($check_cus_biz != NULL)
            {
                $cus_id = $check_cus_biz->id;
            }
            else
            {
                $cus = Users::getRecordByEmail($_POST['email']);
                $new_cus = $this->createCustomerBiz($cus->id, $service->biz->id);
                $cus_id = $new_cus->id;
            }
        }

        // Tạo Appointment
        $staff_time = $_POST['staff_time'];
        $separatedData = explode('_', $staff_time);
        $staff_id = $separatedData[0];
        $time = $separatedData[1];
        $date = strtotime(str_replace('/', '-', $_POST['date']));

        $appointment = new Appoint();
        $appointment->category_id = $service->category_id;
        $appointment->service_id = $s_id;
        $appointment->note = $_POST['note'];
        $appointment->date = $date;
        $appointment->start_time = ltrim($time, '0');
        $appointment->end_time = Utils::plusminute($time, $service->duration, $service->recover);
        $appointment->isbackend = Appoint::BOOKING_ONLINE;
        $appointment->author_id = $staff_id;
        $appointment->type = Appoint::TYPE_APPOINTMENT;
        $appointment->status = Appoint::BOOKING_STATUS_PENDING;


        if ($appointment->save() && $appointment->validate())
        {
            // Gán Appointment với Customer
            $apt_cus = new AptCustomer();
            $apt_cus->apt_id = $appointment->apt_id;
            $apt_cus->customer_id = $cus_id;
            $apt_cus->send_email = AptCustomer::SEND_EMAIL_DISABLE;
            $apt_cus->check_status = AptCustomer::CHECK_STATUS_DEFAULT;

            if ($apt_cus->validate() && $apt_cus->save())
            {
                unset(Yii::app()->session['booking_staff']);
                unset(Yii::app()->session['booking_date']);
                unset(Yii::app()->session['booking_hour']);
//                EmailConfirm::send($customer->email, $customer->name, $appointment->apt_id, $apt_cus->customer->ckey);
                /**
                 * Check periods has discount and get Discount of period
                 * Caculate final price by discount
                 */
                $discount = Hotdeal::getDiscountByTime($appointment->service_id, $appointment->date, $appointment->start_time);
                $discount_value = $discount ? $appointment->service->price * $discount / 100 : 0;
                $tax_value = $appointment->service->user->tax ?
                    $appointment->service->user->tax->value * $appointment->service->price / 100 : 0;
                $final_price = $appointment->service->price - $discount_value + $tax_value;
                $order_id = Orders::createOrder($appointment->apt_id, $apt_cus->customer_id, Orders::STATUS_PENDING, @$discount, TRUE);
                echo json_encode(array(
                    'status' => true,
                    'cus_email' => $apt_cus->customer->email,
                    'cus_name' => $apt_cus->customer->name,
                    'cus_key' => $apt_cus->customer->ckey,
                    'apt_id' => $apt_cus->apt_id,
                    'final_price' => $final_price,
                    'order_id' => $order_id
                ));
                Yii::app()->end();
            }
        }
        else
        {
            echo json_encode(array(
                'status' => false
            ));
            Yii::app()->end();
        }
    }

    /**
     * create new record in tbl_customer
     */
    private function createCustomerBiz($user_id, $biz_id)
    {
        $new_cus = new Customer();
        $new_cus->firstname = $_POST['fname'];
        $new_cus->lastname = $_POST['lname'];
        $new_cus->mobile_phone = $_POST['phone'];
        $new_cus->address = $_POST['address'];
        $new_cus->postal_code = $_POST['postal_code'];
        $new_cus->status = Customer::STATUS_ACTIVE;
        $new_cus->country = Country::DEFAULT_COUNTRY;
        $birthday = ($_POST['birthday'] != '') ? str_replace('/', '-', $_POST['birthday']) : NULL;
        $new_cus->birthday = strtotime($birthday);

        $new_cus->biz_id = $biz_id;
        $new_cus->user_id = $user_id;
        $new_cus->save();
        $new_cus->updateCkey();
        return $new_cus;
    }

    /**
     * create a new customer
     * @return Cactiverecord a signle active record
     */
    private function createNewUser()
    {
        $customer = new CustomerBookForm();
        $customer->firstname = $_POST['fname'];
        $customer->lastname = $_POST['lname'];
        $customer->email = $_POST['email'];
        $customer->mobile_phone = $_POST['phone'];
        $customer->occupation = $_POST['occupation'];
        $birthday = ($_POST['birthday'] != '') ? str_replace('/', '-', $_POST['birthday']) : NULL;
        $customer->birthday = strtotime($birthday);
        $customer->address = $_POST['address'];
        $customer->postal_code = $_POST['postal_code'];
        $customer->country = Country::DEFAULT_COUNTRY;

        $customer->type = Users::TYPE_CUSTOMER;
        $customer->status = Users::STATUS_ACTIVE;
        $customer->date_created = time();

        //gen new random password
        $newPwd = Utils::genRandomString();
        $customer->new_pass = $newPwd;

        $customer->save();

        // send email to new user
        MyEmail::sendToNewUser($customer, $newPwd);

        $customer->completeCreateUser();
        return $customer;
    }

    /**
     * Use at frontend/booking/index?service=3
     * @return list free time of staff
     */
    public function actionGetStaffFreetime()
    {
        //English textual 28/Dec/2013
        $date = strtotime(str_replace('/', '-', $_POST['date']));


        $sid = $_POST['sid'];
        $staff_id = $_POST['staff'];
        $service = Service::getRecordbySid($sid);

        //Biz work time in this date
        $work_day = $service->user->business->work_day;
        $biz_opentime = $service->user->business->open_time;
        //lay gio lam viec trong ngay
        $biz_work_times = Business::getWorkTimesByDay($date, $work_day);

        //neu null thi return
        if ($biz_work_times == NULL)
        {

            echo json_encode(array(
                'morning' => array(),
                'afternoon' => array(),
                'evening' => array(),
            ));

            Yii::app()->end();
        }


        $arr_staff_time = $this->_getFreetime($staff_id, $date, $sid, $biz_work_times, $biz_opentime);

        echo json_encode($arr_staff_time);
        Yii::app()->end();
    }

    /**
     * 
     * @param int $staff staff id
     * @param string $date date time, English textual 28/Dec/2013
     * @param int $sid service id
     * @param string $biz_work_times Business work_time in this day
     * @param integer $biz_opentime Business open_time
     * @return mixed List of avaiable time of staff
     */
    private function _getFreetime($staff, $date, $sid, $biz_work_times, $biz_opentime)
    {
        $arr_staff_time = array();
        $result_arr = array();
        $arr_staff_time_morning = array();
        $arr_staff_time_afternoon = array();
        $arr_staff_time_evening = array();

        $service = Service::model()->findByPk($sid);
        $_cover_time = $service->totalTime; // interger
        $_cover_time_inSecond = $_cover_time * 60;
        //Nếu không select staff
        if ($staff == 0)
        {
            //find all staff
            $service_staffs = ServiceStaff::model()->findAll('sid=:sid', array(
                ':sid' => $sid
                )
            );

            foreach ($service_staffs as $service_staff)
            {
                $staff_id = Users::getIdByUkey($service_staff->sukey);

                $appoint = Appoint::model()->findAll('date=:date AND author_id=:author_id', array(
                    ':date' => $date,
                    ':author_id' => $staff_id
                ));

                //Business Worktime on this day
                $morning = Business::getMinutesStepbyDay(Utils::MORNING, $biz_work_times, $date, $biz_opentime, $_cover_time_inSecond);
                $afternoon = Business::getMinutesStepbyDay(Utils::AFTERNOON, $biz_work_times, $date, $biz_opentime, $_cover_time_inSecond);
                $evening = Business::getMinutesStepbyDay(Utils::EVENING, $biz_work_times, $date, $biz_opentime, $_cover_time_inSecond);

                $arr = array('morning' => $morning, 'afternoon' => $afternoon, 'evening' => $evening);

                /*
                 * Nếu không có appoint nào trong ngày thì Staff free-time cả ngày
                 */
                if ($appoint == NULL)
                {
                    $result_arr_morning = array();
                    foreach ($arr['morning'] as $v)
                    {
                        $discount_by_time = Hotdeal::getDiscountByTime($sid, $date, $v);
                        if ($discount_by_time)
                        {
                            $result_arr_morning[] = array(
                                'value' => $staff_id . '_' . $v,
                                'time' => $v,
                                'discount' => $discount_by_time);
                        }
                        else
                        {
                            $result_arr_morning[] = array(
                                'value' => $staff_id . '_' . $v,
                                'time' => $v);
                        }
                    }
                    $result_arr_afternoon = array();
                    foreach ($arr['afternoon'] as $v)
                    {
                        $discount_by_time = Hotdeal::getDiscountByTime($sid, $date, $v);
                        if ($discount_by_time)
                        {
                            $result_arr_afternoon[] = array(
                                'value' => $staff_id . '_' . $v,
                                'time' => $v,
                                'discount' => $discount_by_time);
                        }
                        else
                        {
                            $result_arr_afternoon[] = array(
                                'value' => $staff_id . '_' . $v,
                                'time' => $v);
                        }
                    }
                    $result_arr_evening = array();
                    foreach ($arr['evening'] as $v)
                    {
                        $discount_by_time = Hotdeal::getDiscountByTime($sid, $date, $v);
                        if ($discount_by_time)
                        {
                            $result_arr_evening[] = array(
                                'value' => $staff_id . '_' . $v,
                                'time' => $v,
                                'discount' => $discount_by_time);
                        }
                        else
                        {
                            $result_arr_evening[] = array(
                                'value' => $staff_id . '_' . $v,
                                'time' => $v);
                        }
                    }

                    $result_arr['morning'] = $result_arr_morning;
                    $result_arr['afternoon'] = $result_arr_afternoon;
                    $result_arr['evening'] = $result_arr_evening;

                    echo json_encode($result_arr);
                    Yii::app()->end();
                }
                else
                {
                    $busy_array = $this->_getBusyTime($appoint, $service);
                    foreach ($busy_array as $busy_time)
                    {
                        //remove busy time
                        $morning_busy = array_search($busy_time, $morning);
                        $afternoon_busy = array_search($busy_time, $afternoon);
                        $evening_busy = array_search($busy_time, $evening);
                        if ($morning_busy !== FALSE)
                        {
                            unset($morning[$morning_busy]);
                        }
                        if ($afternoon_busy !== FALSE)
                        {
                            unset($afternoon[$afternoon_busy]);
                        }
                        if ($evening_busy !== FALSE)
                        {
                            unset($evening[$evening_busy]);
                        }
                    }
                    /*
                     * Viết lại array
                     */
                    $result_arr = array();
                    $result_arr_morning = array();
                    foreach ($morning as $v)
                    {
                        $result_arr_morning[] = $v;
                    }

                    $result_arr_afternoon = array();
                    foreach ($afternoon as $v)
                    {
                        $result_arr_afternoon[] = $v;
                    }
                    $result_arr_evening = array();
                    foreach ($evening as $v)
                    {
                        $result_arr_evening[] = $v;
                    }


                    $result_arr['morning'] = $result_arr_morning;
                    $result_arr['afternoon'] = $result_arr_afternoon;
                    $result_arr['evening'] = $result_arr_evening;
                }
                //rewrite array: time=>staff
                foreach ($result_arr['morning'] as $v)
                {
                    $arr_staff_time_morning[$v] = $staff_id;
                }
                foreach ($result_arr['afternoon'] as $v)
                {
                    $arr_staff_time_afternoon[$v] = $staff_id;
                }
                foreach ($result_arr['evening'] as $v)
                {
                    $arr_staff_time_evening[$v] = $staff_id;
                }
            }

            //sort time by key
            ksort($arr_staff_time_morning);
            ksort($arr_staff_time_afternoon);
            ksort($arr_staff_time_evening);
            $arr_staff_time = array(
                'morning' => $arr_staff_time_morning,
                'afternoon' => $arr_staff_time_afternoon,
                'evening' => $arr_staff_time_evening
            );
        }
        else
        {
            //Lấy các appoint theo staff đó
            $appoint = Appoint::model()->findAll('date=:date AND author_id=:author_id', array(
                ':date' => $date,
                ':author_id' => $staff
            ));

            //Business Worktimes on this day
            $morning = Business::getMinutesStepbyDay(Utils::MORNING, $biz_work_times, $date, $biz_opentime, $_cover_time_inSecond);
            $afternoon = Business::getMinutesStepbyDay(Utils::AFTERNOON, $biz_work_times, $date, $biz_opentime, $_cover_time_inSecond);
            $evening = Business::getMinutesStepbyDay(Utils::EVENING, $biz_work_times, $date, $biz_opentime, $_cover_time_inSecond);

            $arr = array('morning' => $morning, 'afternoon' => $afternoon, 'evening' => $evening);
            /*
             * Nếu không có appoint nào trong ngày thì Staff free-time cả ngày
             */
            if ($appoint == NULL)
            {
                foreach ($arr['morning'] as $v)
                {
                    $discount_by_time = Hotdeal::getDiscountByTime($sid, $date, $v);
                    if ($discount_by_time)
                    {
                        $result_arr_morning[] = array(
                            'value' => $staff_id . '_' . $v,
                            'time' => $v,
                            'discount' => $discount_by_time);
                    }
                    else
                    {
                        $result_arr_morning[] = array(
                            'value' => $staff_id . '_' . $v,
                            'time' => $v);
                    }
                }
                foreach ($arr['afternoon'] as $v)
                {
                    $discount_by_time = Hotdeal::getDiscountByTime($sid, $date, $v);
                    if ($discount_by_time)
                    {
                        $result_arr_afternoon[] = array(
                            'value' => $staff_id . '_' . $v,
                            'time' => $v,
                            'discount' => $discount_by_time);
                    }
                    else
                    {
                        $result_arr_afternoon[] = array(
                            'value' => $staff_id . '_' . $v,
                            'time' => $v);
                    }
                }
                foreach ($arr['evening'] as $v)
                {
                    $discount_by_time = Hotdeal::getDiscountByTime($sid, $date, $v);
                    if ($discount_by_time)
                    {
                        $result_arr_evening[] = array(
                            'value' => $staff_id . '_' . $v,
                            'time' => $v,
                            'discount' => $discount_by_time);
                    }
                    else
                    {
                        $result_arr_evening[] = array(
                            'value' => $staff_id . '_' . $v,
                            'time' => $v);
                    }
                }
                $result_arr['morning'] = $result_arr_morning;
                $result_arr['afternoon'] = $result_arr_afternoon;
                $result_arr['evening'] = $result_arr_evening;

                echo json_encode($result_arr);
                Yii::app()->end();
            }
            else
            {
                $busy_array = $this->_getBusyTime($appoint, $service);
                foreach ($busy_array as $busy_time)
                {
                    //remove busy time
                    $morning_busy = array_search($busy_time, $morning);
                    $afternoon_busy = array_search($busy_time, $afternoon);
                    $evening_busy = array_search($busy_time, $evening);
                    if ($morning_busy !== FALSE)
                    {
                        unset($morning[$morning_busy]);
                    }
                    if ($afternoon_busy !== FALSE)
                    {
                        unset($afternoon[$afternoon_busy]);
                    }
                    if ($evening_busy !== FALSE)
                    {
                        unset($evening[$evening_busy]);
                    }
                }
                foreach ($morning as $v)
                {
                    $result_arr_morning[] = $v;
                }
                foreach ($afternoon as $v)
                {
                    $result_arr_afternoon[] = $v;
                }
                foreach ($evening as $v)
                {
                    $result_arr_evening[] = $v;
                }
                $result_arr['morning'] = $result_arr_morning;
                $result_arr['afternoon'] = $result_arr_afternoon;
                $result_arr['evening'] = $result_arr_evening;

                //rewrite array: time=>staff
                foreach ($result_arr['morning'] as $v)
                {
                    $arr_staff_time_morning[$v] = $staff;
                }
                foreach ($result_arr['afternoon'] as $v)
                {
                    $arr_staff_time_afternoon[$v] = $staff;
                }
                foreach ($result_arr['evening'] as $v)
                {
                    $arr_staff_time_evening[$v] = $staff;
                }
                //sort time
                ksort($arr_staff_time_morning);
                ksort($arr_staff_time_afternoon);
                ksort($arr_staff_time_evening);
                $arr_staff_time = array(
                    'morning' => $arr_staff_time_morning,
                    'afternoon' => $arr_staff_time_afternoon,
                    'evening' => $arr_staff_time_evening,
                );
            }
        }

        $arr_morning = array();

        foreach ($arr_staff_time['morning'] as $time => $staff)
        {
            $discount_by_time = Hotdeal::getDiscountByTime($sid, $date, $time);
            if ($discount_by_time)
            {
                $arr_morning[] = array(
                    'value' => $staff_id . '_' . $time,
                    'time' => $time,
                    'discount' => $discount_by_time);
            }
            else
            {
                $arr_morning[] = array(
                    'value' => $staff_id . '_' . $time,
                    'time' => $time);
            }
        }
        $arr_afternoon = array();
        foreach ($arr_staff_time['afternoon'] as $time => $staff)
        {
            $discount_by_time = Hotdeal::getDiscountByTime($sid, $date, $time);
            if ($discount_by_time)
            {
                $arr_afternoon[] = array(
                    'value' => $staff_id . '_' . $time,
                    'time' => $time,
                    'discount' => $discount_by_time);
            }
            else
            {
                $arr_afternoon[] = array(
                    'value' => $staff_id . '_' . $time,
                    'time' => $time);
            }
        }
        $arr_evening = array();
        foreach ($arr_staff_time['evening'] as $time => $staff)
        {
            $discount_by_time = Hotdeal::getDiscountByTime($sid, $date, $time);
            if ($discount_by_time)
            {
                $arr_evening[] = array(
                    'value' => $staff_id . '_' . $time,
                    'time' => $time,
                    'discount' => $discount_by_time);
            }
            else
            {
                $arr_evening[] = array(
                    'value' => $staff_id . '_' . $time,
                    'time' => $time);
            }
        }

        $staff_time['morning'] = $arr_morning;
        $staff_time['afternoon'] = $arr_afternoon;
        $staff_time['evening'] = $arr_evening;

        echo json_encode($staff_time);
        Yii::app()->end();
    }

    private function _getBusyTime($appoint, $service)
    {
        $busy_merge = array();

        foreach ($appoint as $apt)
        {
            //round recover
            $start_stamp = strtotime($apt->start_time) - (($service->recover + $service->duration) * 60);
            $start = date('G:i', $start_stamp);
            //list busy time
            /*
             * Thêm busy time tạo trong backend
             */
            $busy_times[] = Utils::minuteStep(5, $start, $apt->end_time, FALSE);
            foreach ($busy_times as $v)
            {
                $busy_merge = array_merge($v, $busy_merge);
            }
        }

        //remove dup
        $busy_array = array_unique($busy_merge);
        return $busy_array;
    }

    /**
     * Use PDT method
     * Before: Turn on PDT method on paypal merchant account; Setup sandbox or live;
     * Define method Sandbox or live, Define indentify token
     */
    public function actionPaypal()
    {
        $tx = $_REQUEST['tx']; //transaction ID
        $data = Payment::getPaypalReturnData($tx);
        if ($data)
        {
            $order_id = $data['item_number1']; //This is order key

            $order = Orders::model()->findByPk($order_id);
            $order->status = Orders::STATUS_COMPLETED;
            $order->save();

            /**
             * Update appoint status
             */
            if ($order->appoint->type == Appoint::TYPE_APPOINTMENT)
            {
                Appoint::model()->updateByPk($order->apt_id, array('status' => Appoint::STATUS_CHECKOUT));
            }
            elseif ($order->appoint->type == Appoint::TYPE_ROOM)
            {
                $apt_cus = AptCustomer::model()->find("apt_id=:a AND customer_id=:c", array(
                    ":a" => $order->apt_id,
                    ":c" => $order->customer->id
                ));
                $apt_cus->status = AptCustomer::CHECK_STATUS_CHECKOUT;
                $apt_cus->save();
            }

            //Create Receipt Record
            $receipt = new Receipt();
            $receipt->discount = $order->hotdeal_discount;
            $receipt->discount_type = '%';
            $receipt->final_price = $data['mc_gross'];
            $receipt->list_price = $order->s_price;
            $receipt->order_id = $order->order_id;
            $tax_value = $order->s_price * $order->tax / 100;
            $receipt->tax = $tax_value; //Giá trị tax đã tính
            $receipt->qty = 1;
            $receipt->receipt_date = time();
            $receipt->item_description = "<b>{$order->service->s_name}</b><br/>";
            $receipt->item_description .= $order->formartDate() . "<br/>";
            $receipt->item_description .= "Duration: {$order->service->duration} minute<br/>";
            $receipt->item_description .= "Booking: #$order->apt_id<br/>";

            /**
             * Create Payment Record
             */
            $payment = Payment::model()->find("order_id=:o", array(':o' => $order_id));
            if (!$payment)
            {
                $payment = new Payment();
                $payment->amount = $data['mc_gross'];
                $payment->method = Payment::METHOD_PAYPAL;
                $payment->order_id = $order->order_id;
                $payment->payment_date = time();
                $payment->type = Payment::TYPE_APPOINT;
                $payment->log = serialize($data);
            }
            if ($payment->save())
            {
                $payment->payment_key = $payment->genPaymentKey();
                $payment->save();
                //Send Confirm Email
                $isc_file = Helper::createICSFile($order->appoint, $order->customer);
                MyEmail::NewAppointToCus($order->appoint, $order->customer, $isc_file);
                MyEmail::NewAppointToBiz($order->appoint, $order->customer, $isc_file);
                MyEmail::NewAppointToStaff($order->appoint, $order->customer, $isc_file);
                Yii::app()->user->setFlash('success', Yii::t('frontend','Payment Transaction Successfully!'));
            }

            if ($receipt->save())
            {
                $receipt->receipt_key = $receipt->genReceiptKey();
                $receipt->save();
            }

            $hotdeal = $order->service->hotdeal;
        }
        else
        {
            Yii::app()->user->setFlash('error', Yii::t('frontend','Transaction Cancelled'));
        }

        $this->render('booking/paypal', array('hotdeal' => @$hotdeal));
    }

}

/** 
* End file SearchController
*/